<template>
  <div>
    <el-upload
      list-type="picture-card"
      action="#"
      :file-list="fileList"
      :class="{disable:fileList.length>0}"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="uploadImg"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条 -->
    <el-progress v-if="isShowProgress" :text-inside="true" :stroke-width="16" :percentage="percent" style="width:150px" />

    <el-dialog :visible="isShow" title="预览" @close="closeFn">
      <img :src="imgStr" alt="">
    </el-dialog>
  </div>

</template>
<script>
// var COS = require('cos-js-sdk-v5')
import COS from 'cos-js-sdk-v5'
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDzoOGsDKAi4E7k59xUjhPq2xc07xWpse9',
  SecretKey: 'GFyPaU7TdW8SVIo2zg5D4g1HGyPZS4PT'
})
export default {
  data() {
    return {
      fileList: [
        // { url: 'https://img1.baidu.com/it/u=386832729,264495465&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500' }
      ],
      isShow: false,
      imgStr: '',
      percent: 0,
      isShowProgress: false
    }
  },
  methods: {
    // 文件预览回调
    onPreview(file) {
      this.isShow = true
      this.imgStr = file.url
    },
    // 关闭弹窗
    closeFn() {
      this.isShow = false
    },
    // 文件删除触发的回调
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    // 文件变化触发的回调
    onChange(file, fileList) {
      this.fileList = fileList
    },
    // 上传前的回调 用于判断文件是否符合要求
    beforeUpload(file) {
    //   console.log(file)
      // 限制大小
      const maxSize = 10 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.warning('图片大小不能超过2M')
        return false
      }
      // 限制文件类型
      const whiteList = ['image/jpeg', 'image/png', 'image/gif']
      if (!whiteList.includes(file.type)) {
        this.$message.warning('图片仅支持jpeg，png，gif')
        return false
      }
    },
    uploadImg(params) {
    //   console.log(76, params)
      //   console.log('上传')
      this.isShowProgress = true
      cos.putObject({
        Bucket: 'mikumiku-1308572180', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 (文件名)*/
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
        //   console.log(88, progressData)
          //   console.log(JSON.stringify(progressData))
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        // 上传完成后，需要手动告诉饿了么ui状态
        // 需要给url地址进行拼接
        this.fileList[0].url = 'http://' + data.Location
        this.fileList[0].status = 'success'
        setTimeout(() => {
          this.isShowProgress = false
        }, 1000)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.disable{
::v-deep.el-upload--picture-card{
display: none;
}}
img{
    width: 100%;
}
</style>
